package impl

import (
	"context"

	"gitee.com/shiwjlinux/arm/apps/host"
	"gitee.com/shiwjlinux/arm/common"
	"gitee.com/shiwjlinux/arm/exception"
	"gorm.io/gorm"
)

// CreateHost 创建主机
func (i *Impl) CreateHost(ctx context.Context,
	in *host.CreateHostRequest,
) (*host.Host, error) {
	// TODO: 还没想好，主机名怎么设置
	if in.Hostname == "" {
		in.Hostname = in.Sn
	}

	// 检验
	if err := common.Validate(in); err != nil {
		return nil, exception.ErrorEmpty
	}

	ins := host.NewHost(in)

	if err := i.db.
		Model(&host.Host{}).
		WithContext(ctx).
		Create(ins).Error; err != nil {
		return nil, exception.ErrorFailed
	}

	return ins, nil
}

func (i *Impl) QueryHost(ctx context.Context,
	in *host.QueryHostRequest,
) (*host.HostSet, error) {
	set := host.NewHostSet()
	query := i.db.Model(&host.Host{}).WithContext(ctx)

	if in.Keywords != "" {
		query = query.Where("summary like ?", "%"+in.Keywords+"%")
	}
	if in.Hostname != "" {
		query = query.Where("hostname like ?", "%"+in.Hostname+"%")
	}
	if in.Sn != "" {
		query = query.Where("sn = ?", in.Sn)
		// query = query.Where("sn like ?", "%"+in.Sn+"%")
	}

	if err := query.Count(&set.Total).Error; err != nil {
		return nil, exception.ErrorFailed
	}

	if err := query.
		Offset(in.Offect()).
		Limit(in.PageSize).
		Find(&set.Items).Error; err != nil {
		return nil, exception.ErrorFailed
	}
	return set, nil
}

// UpdateHost 更新Host
func (i *Impl) UpdateHost(ctx context.Context,
	in *host.UpdateHostRequest,
) (*host.Host, error) {

	ins, err := i.DescribeHost(ctx, host.NewDescribeHostRequest(in.Id))
	if err != nil {
		return nil, err
	}

	// in.CreateHostRequest 客户端提交的数据
	ins.CreateHostRequest = in.CreateHostRequest

	if err := i.db.
		Model(&host.Host{}).
		WithContext(ctx).
		Where("id = ?", in.Id).
		Updates(ins).Error; err != nil {
		return nil, err
	}
	return ins, nil
}

func (i *Impl) DeleteHost(ctx context.Context,
	in *host.DeleteHostRequest,
) (*host.Host, error) {
	if err := common.Validate(in); err != nil {
		return nil, exception.ErrorEmpty
	}

	// 获取主机信息
	ins, err := i.DescribeHost(ctx, host.NewDescribeHostRequest(in.Id))
	if err != nil {
		return nil, err
	}

	if err := i.db.
		Model(&host.Host{}).
		WithContext(ctx).
		Where("id = ?", in.Id).
		Delete(ins).Error; err != nil {
		return nil, exception.ErrorFailed
	}

	return ins, nil
}

func (i *Impl) DescribeHost(ctx context.Context,
	in *host.DescribeHostRequest,
) (*host.Host, error) {
	if err := common.Validate(in); err != nil {
		return nil, exception.ErrorEmpty
	}

	ins := host.DefaultHost()

	if err := i.db.
		Model(&host.Host{}).
		WithContext(ctx).
		Where("id = ?", in.Id).
		First(ins).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, exception.ErrorNotFound
		}
		return nil, exception.ErrorFailed
	}

	return ins, nil
}
